package com.nightsoul.jsch.test;

import java.util.Map;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class ExecChannel {
	private Session session;
	private Channel channel;
	
	
	public ChannelExec openChannel(Map<String, String> sftpAuth, int timeout) throws Exception {
		String host = sftpAuth.get("host");
		String port = sftpAuth.get("port");
		String username = sftpAuth.get("username");
		String password = sftpAuth.get("password");
		
		int sftpPort = port==null ? 22 : Integer.valueOf(port);
		
		JSch jSch = new JSch();
		session = jSch.getSession(username, host, sftpPort);
		if(password!=null) {
			session.setPassword(password);
		}
		Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setTimeout(timeout);
        session.connect();
        
        channel = session.openChannel("exec");
		
		return (ChannelExec) channel;
	}
	
	public void closeChannel() throws Exception {
		if(channel!=null) {
			channel.disconnect();
		}
		if(session!=null) {
			session.disconnect();
		}
	}
}
